package com.briup.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/13
 * @Description:
 */
class Printer {

    // 普通同步方法：锁对象默认为this
    public synchronized void print1() {
        System.out.print("天");
        System.out.print("天");
        System.out.print("向");
        System.out.print("上");
        System.out.println();
    }

    public void print2() {
        // 同步代码块，也使用this作为锁对象
        // 测试时，可以注释同步代码块，或使用其他锁对象，然后观察程序运行

        // synchronized (Printer.class) {
        synchronized (this) {
            System.out.print("努");
            System.out.print("力");
            System.out.print("学");
            System.out.print("习");
            System.out.println();
        }
    }
}
public class Test09 {
    public static void main(String[] args) {
        Printer p=new Printer();
        Thread t1=new Thread(()->{
            for (int i = 0; i < 100; i++) {
                p.print1();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2=new Thread(()->{
            for (int i = 0; i < 100; i++) {
                p.print2();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
